import { createStore } from "vuex";
import API from '../api/api'

export default createStore({
  state: {
    user: sessionStorage.getItem('user') || '',
    token: sessionStorage.getItem('token') || ''
  },
  getters: {
    GET_USER(state) {
      return state.user
    },
    GET_TOKEN(state) {
      return state.token
    }
  },
  mutations: {
    SAVE_USER(state,info) {
      state.user = info
    },
    SAVE_TOKEN(state,info) {
      state.user = info
    },
  },
  actions: {
    POST_TOKEN({commit}) {
      return new Promise(() => {
        API.GET_TOKEN().then((res:any) => {
          sessionStorage.setItem('token',res.token)
          commit('SAVE_TOKEN',res.token)
        })
      })
    },
    POST_USER({commit}) {
      return new Promise(() => {
        API.POST_USER().then((res:any) => {
          sessionStorage.setItem('user',res.user)
          commit('SAVE_USER',res.user)
        })
      })
    },
  },
  modules: {},
  strict: true
});
